﻿using System.IdentityModel.Tokens.Jwt;
using System.Text.Json;
using Api.Shared.Model.Dto;
using Api.Shared.Model.XinYa;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Api.Shared.Utils.MyClient;
using AutoMapper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace FitterTest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class XyController : ControllerBase
    {
        private readonly ISugarClientService mysqlService;
        private readonly IHttpClientFactory clientFactory;
        private readonly ILogger<XyController> logger;
        private readonly IMapper mapper;

        public XyController(
            [FromKeyedServices(nameof(SqlName.mysql))] ISugarClientService mysqlService,
            IHttpClientFactory clientFactory,
            ILogger<XyController> logger,
            IMapper mapper
        )
        {
            this.mysqlService = mysqlService;
            this.clientFactory = clientFactory;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 楷新向新亚提交控制数据
        /// </summary>
        /// <param name="person"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<XyApiResponse<KxToXyControlMsg>> KxToXyControlMsg(
            [FromBody] KxToXyControlMsg xyControlMsg
        )
        {
            KxToXyControlMsg controlMsg =
                new()
                {
                    Start = "1",
                    Stop = "0",
                    TaskNum = "5"
                };

            XyApiResponse<KxToXyControlMsg>? resp =
                new()
                {
                    Message = "Success!",
                    Result = controlMsg,
                    Status = true,
                    Code = 200
                };
            return resp;
        }

        [HttpGet]
        public ActionResult<XyApiResponse<XyData>> GetData()
        {
            XyData xy = new() { TaskStauts = "2", VoltagePer = "40" };
            XyApiResponse<XyData>? resp =
                new()
                {
                    Message = "Success!",
                    Result = xy,
                    Status = true,
                    Code = 200
                };
            return resp;
        }

        [HttpPost]
        public async Task<IActionResult> AddReport([FromBody] TestReport testReport)
        {
            var c = await mysqlService
                .Db.InsertNav(testReport)
                .Include(x => x.TestRecords)
                .ExecuteCommandAsync();

            if (c)
            {
                return Ok();
            }
            else
            {
                return BadRequest("204");
            }
        }

        [HttpGet]
        public async Task<IActionResult> TestPost()
        {
            IConfigurationRoot? buider = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();
            string ip = buider["myIp"] ?? string.Empty;
            using HttpClient? client = clientFactory.CreateClient();
            client.Timeout = TimeSpan.FromSeconds(20);
            client.BaseAddress = new Uri(ip);
            TestReport testReport =
                new()
                {
                    ModelName = "t1",
                    Operator = "o1",
                    ProductName = "p1",
                    ReportTime = DateTime.Now,
                    SerialNumber = "11",
                    TestType = 1,
                    TestRecords =
                    [
                        new TestRecord
                        {
                            InputCurrent = 55,
                            InputVoltage = 66.1,
                            Number = 1,
                            OutputCurrent = 32,
                            OutputVoltage = 67.1,
                            TestPC = 53.1,
                            Time = DateTime.Now
                        },
                        new TestRecord
                        {
                            InputCurrent = 555,
                            InputVoltage = 766.1,
                            Number = 2,
                            OutputCurrent = 332,
                            OutputVoltage = 637.1,
                            TestPC = 523.5,
                            Time = DateTime.Now
                        }
                    ]
                };
            var baseRequest = new BaseRequest
            {
                Method = HttpMethod.Post,
                Route = "/api/Xy/MyAddReport",
                Parameter = testReport
            };
            //MyHttpClient myHttpClient = new(ip, client);
            MyHttpClient myHttpClient = new(client, "myIp");
            var response = await myHttpClient.ExecuteAsync<TestRecord>(baseRequest);
            JsonSerializerOptions options =
                new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, };
            var str = JsonSerializer.Serialize(response, options);
            logger.LogInformation($"started返回值: {str}");
            //double ac = 0;
            //int aaa = 0;
            //short bbb = 0;
            //Interlocked.Exchange(ref ac, 1.5);
            //Interlocked.Exchange(ref aaa , bbb);
            return Ok();
        }

        [HttpPost]
        public async Task<ActionResult<XyApiResponse<TestReport>>> MyAddReport(
            [FromBody] TestReport testReport
        )
        {
            var c = await mysqlService
                .Db.InsertNav(testReport)
                .Include(x => x.TestRecords)
                .ExecuteCommandAsync();

            if (c)
            {
                XyApiResponse<TestReport>? resp =
                    new()
                    {
                        Message = "Success!",
                        Result = testReport,
                        Status = true,
                        Code = 200
                    };
                return resp;
            }
            else
            {
                return BadRequest("204");
            }
        }

        [HttpGet]
        public async Task<ActionResult<XyApiResponse<TestReport>>> GetReport([FromQuery] int id)
        {
            TestReportDto? report = await mysqlService
                .Db.Queryable<TestReportDto>()
                .Includes(x => x.TestRecords)
                .FirstAsync(x => x.Id == id);
            if (report == null)
            {
                return NotFound("未找到报告");
            }

            var reportDto = mapper.Map<TestReportDto>(report);

            JsonSerializerOptions options =
                new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, };
            var str = JsonSerializer.Serialize(reportDto, options);

            XyApiResponse<TestReport>? resp =
                new()
                {
                    Message = $"Success:{str} ",
                    Result = new(),
                    Status = true,
                    Code = 200
                };

            // 为了修复 CA2254，应该使用消息模板而不是字符串插值或串联
            logger.LogWarning("{ReportJson}", str ?? string.Empty);
            return resp;
        }
    }
}
